const db = require('../config/database');
const logger = require('../utils/logger');

/**
 * 商品规格管理控制器（简化版）
 * 支持单层规格配置
 */
class SpecController {
  /**
   * 获取商品的所有规格（前台+后台）
   * GET /api/specs/:productId
   */
  async getSpecs(req, res) {
    try {
      const { productId } = req.params;
      const { status } = req.query; // 前台只查询启用的，后台可查询所有

      let sql = 'SELECT * FROM product_specs WHERE product_id = ?';
      const params = [productId];

      if (status !== undefined) {
        sql += ' AND status = ?';
        params.push(status);
      }

      sql += ' ORDER BY sort_order DESC, id ASC';

      const [specs] = await db.query(sql, params);

      // 确保price字段是数字类型（MySQL的DECIMAL可能返回字符串）
      const specsWithNumbers = specs.map(spec => ({
        ...spec,
        price: spec.price ? parseFloat(spec.price) : null,
        stock: spec.stock !== null ? parseInt(spec.stock) : -1
      }));

      res.json({
        success: true,
        data: specsWithNumbers
      });
    } catch (error) {
      logger.error('获取商品规格失败', { error: error.message, productId: req.params.productId });
      res.json({ success: false, message: '系统错误' });
    }
  }

  /**
   * 获取单个规格详情
   * GET /api/specs/detail/:id
   */
  async getSpecDetail(req, res) {
    try {
      const { id } = req.params;

      const [specs] = await db.query(
        'SELECT * FROM product_specs WHERE id = ?',
        [id]
      );

      if (specs.length === 0) {
        return res.json({ success: false, message: '规格不存在' });
      }

      res.json({
        success: true,
        data: specs[0]
      });
    } catch (error) {
      logger.error('获取规格详情失败', { error: error.message, id: req.params.id });
      res.json({ success: false, message: '系统错误' });
    }
  }

  /**
   * 创建商品规格（后台管理）
   * POST /api/admin/specs
   */
  async createSpec(req, res) {
    try {
      const { product_id, spec_name, spec_value, price, stock, image, sort_order, status } = req.body;

      if (!product_id || !spec_name || !spec_value) {
        return res.json({
          success: false,
          message: '商品ID、规格名称和规格值不能为空'
        });
      }

      // 检查商品是否存在
      const [products] = await db.query('SELECT id FROM products WHERE id = ?', [product_id]);
      if (products.length === 0) {
        return res.json({ success: false, message: '商品不存在' });
      }

      // 检查是否已存在相同规格
      const [existing] = await db.query(
        'SELECT id FROM product_specs WHERE product_id = ? AND spec_name = ? AND spec_value = ?',
        [product_id, spec_name, spec_value]
      );

      if (existing.length > 0) {
        return res.json({
          success: false,
          message: '该规格已存在'
        });
      }

      const [result] = await db.query(
        `INSERT INTO product_specs (product_id, spec_name, spec_value, price, stock, image, sort_order, status, created_at) 
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())`,
        [product_id, spec_name, spec_value, price || null, stock !== undefined ? stock : -1, image || null, sort_order || 0, status !== undefined ? status : 1]
      );

      logger.success('创建商品规格成功', { id: result.insertId, product_id, spec_name, spec_value });

      res.json({
        success: true,
        message: '创建成功',
        data: { id: result.insertId }
      });
    } catch (error) {
      logger.error('创建商品规格失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  /**
   * 更新商品规格（后台管理）
   * PUT /api/admin/specs/:id
   */
  async updateSpec(req, res) {
    try {
      const { id } = req.params;
      const { spec_name, spec_value, price, stock, image, sort_order, status } = req.body;

      const updates = [];
      const values = [];

      if (spec_name !== undefined) {
        updates.push('spec_name = ?');
        values.push(spec_name);
      }

      if (spec_value !== undefined) {
        updates.push('spec_value = ?');
        values.push(spec_value);
      }

      if (price !== undefined) {
        updates.push('price = ?');
        values.push(price || null);
      }

      if (stock !== undefined) {
        updates.push('stock = ?');
        values.push(stock);
      }

      if (image !== undefined) {
        updates.push('image = ?');
        values.push(image || null);
      }

      if (sort_order !== undefined) {
        updates.push('sort_order = ?');
        values.push(sort_order);
      }

      if (status !== undefined) {
        updates.push('status = ?');
        values.push(status);
      }

      if (updates.length === 0) {
        return res.json({ success: false, message: '没有要更新的内容' });
      }

      values.push(id);

      const [result] = await db.query(
        `UPDATE product_specs SET ${updates.join(', ')}, updated_at = NOW() WHERE id = ?`,
        values
      );

      if (result.affectedRows === 0) {
        return res.json({ success: false, message: '规格不存在' });
      }

      logger.success('更新商品规格成功', { id });

      res.json({
        success: true,
        message: '更新成功'
      });
    } catch (error) {
      logger.error('更新商品规格失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  /**
   * 删除商品规格（后台管理）
   * DELETE /api/admin/specs/:id
   */
  async deleteSpec(req, res) {
    try {
      const { id } = req.params;

      // 检查是否有订单使用了该规格
      const [orders] = await db.query(
        "SELECT COUNT(*) as count FROM orders WHERE spec_info LIKE ? AND status IN (0, 1)",
        [`%"spec_id":${id}%`]
      );

      if (orders[0].count > 0) {
        return res.json({
          success: false,
          message: '该规格存在未完成的订单，无法删除'
        });
      }

      const [result] = await db.query('DELETE FROM product_specs WHERE id = ?', [id]);

      if (result.affectedRows === 0) {
        return res.json({ success: false, message: '规格不存在' });
      }

      logger.success('删除商品规格成功', { id });

      res.json({
        success: true,
        message: '删除成功'
      });
    } catch (error) {
      logger.error('删除商品规格失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  /**
   * 批量创建规格（后台管理）
   * POST /api/admin/specs/batch
   */
  async batchCreateSpecs(req, res) {
    try {
      const { product_id, specs } = req.body;

      if (!product_id || !Array.isArray(specs) || specs.length === 0) {
        return res.json({
          success: false,
          message: '商品ID和规格列表不能为空'
        });
      }

      // 检查商品是否存在
      const [products] = await db.query('SELECT id FROM products WHERE id = ?', [product_id]);
      if (products.length === 0) {
        return res.json({ success: false, message: '商品不存在' });
      }

      const connection = await db.getConnection();
      await connection.beginTransaction();

      try {
        let successCount = 0;

        for (const spec of specs) {
          const { spec_name, spec_value, price, stock, image, sort_order, status } = spec;

          if (!spec_name || !spec_value) {
            continue; // 跳过无效数据
          }

          // 检查是否已存在
          const [existing] = await connection.query(
            'SELECT id FROM product_specs WHERE product_id = ? AND spec_name = ? AND spec_value = ?',
            [product_id, spec_name, spec_value]
          );

          if (existing.length > 0) {
            continue; // 跳过已存在的
          }

          await connection.query(
            `INSERT INTO product_specs (product_id, spec_name, spec_value, price, stock, image, sort_order, status, created_at) 
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())`,
            [product_id, spec_name, spec_value, price || null, stock !== undefined ? stock : -1, image || null, sort_order || 0, status !== undefined ? status : 1]
          );

          successCount++;
        }

        await connection.commit();

        logger.success('批量创建商品规格成功', { product_id, count: successCount });

        res.json({
          success: true,
          message: `成功创建 ${successCount} 个规格`,
          data: { count: successCount }
        });
      } catch (error) {
        await connection.rollback();
        throw error;
      } finally {
        connection.release();
      }
    } catch (error) {
      logger.error('批量创建商品规格失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }
}

module.exports = new SpecController();

